package jwebtester.business.beans.competencies;

import java.util.List;

import jwebtester.business.services.SessionMapService;
import jwebtester.business.utils.Dialogs;
import jwebtester.business.utils.DialogsHelper;
import jwebtester.business.utils.FacesHelper;
import jwebtester.dal.provider.CompetenciesDataProvider;
import infrastructure.Scopes;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.JDBCException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import domain.entities.Competency;

@Component
@Scope(Scopes.Request)
public class DeleteCompetencyBean {

	private static final Logger LOG = LoggerFactory.getLogger(DeleteCompetencyBean.class);

	@Autowired
	private transient CompetenciesDataProvider dataProvider;

	@Autowired
	private transient SessionMapService sessionService;

	private Competency competency;

	public void beforeRemoveCompetency(Competency competency) {
		if (competency == null) {
			return;
		}

		this.competency = competency;

		int organizationID = sessionService.getCurrentOrganizationID();
		List<Competency> childs = dataProvider.getCompetencies(organizationID, competency.getId());

		if (childs.size() > 0) {
			new FacesHelper().error("Can't delete competency", String.format(
					"Competency \"%s\" has %s childs. "
							+ "Please move childs to another competency before removing parent",
					competency.getName(), childs.size()));
		} else {
			new DialogsHelper().showDialog(Dialogs.CONFIRM_REMOVE_COMPETENCY);
		}
	}

	public String getMessage() {
		if (competency == null)
			return StringUtils.EMPTY;

		return String.format("Do you really want to remove competency \"%s\"?",
				competency.getName());
	}

	public void remove(Competency competency) {
		try {
			dataProvider.deleteCompetency(competency.getId());

			new FacesHelper().info("Success",
					String.format("Competency \"%s\" has been deleted", competency.getName()));
		} catch (JDBCException ex) {
			LOG.error("Error deleting competency", ex);
			new FacesHelper().info("Error", String.format(
					"Error deleting competency \"%s\". See log for details", competency.getName()));
		}

	}

	public Competency getCompetency() {
		return competency;
	}

	public void setCompetency(Competency competency) {
		this.competency = competency;
	}

}
